package org.jaaksi.demo.gb;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * Created by Fcy on 2015/3/28.<br/>
 * 动态注册广播可以在应用销毁时不在监听
 */
public class MyGbReceiver extends BroadcastReceiver {
    private ReceiveListener listener;

    /**
     * 如果提供 setListener()方法，可以不再构成方法中设置参数
     *
     * @param listener
     */
    public void setListener(ReceiveListener listener) {
        this.listener = listener;
    }

    public MyGbReceiver(ReceiveListener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // new Intent(String action); // 以这种方法
        String action = intent.getAction(); // action = android.net.conn.CONNECTIVITY_CHANGE
        Log.i("&&", "广播action:" + action);
        String msg = intent.getStringExtra("msg");
        Log.i("&&", "收到消息：" + msg); // msg = null


        // 显示通知
        // 回调
        if (listener != null) {
            listener.callBack();
            // TODO 检查是否有网络
            // 应用程序的注册广播的Activity启动时（onStart()调用时），也会触发这个回调（不管网络有没有变化）
            boolean connected = CommonUtils.isConnected(context);
            listener.isNetIn(connected);
        }

    }

    public interface ReceiveListener {
        public void callBack();

        public void isNetIn(boolean isNetIn);
    }
}
